import express, { Request, Response } from 'express';
import { AccountManager } from '../auth/AccountManager';
import { body, validationResult } from 'express-validator';
import { ThirdPartyAuth } from '../auth/ThirdPartyAuth';
import {authenticateJWT} from "../middleware/authMiddleware";
import { verifyToken, generateAccessToken } from '../auth/token';
import path from "path";

const router = express.Router();
const am = new AccountManager();
const auth = new ThirdPartyAuth('yourAppId', 'yourAppSecret');

// 中间件：解析 JSON 请求体
router.use(express.json());

// 中间件：处理跨域请求
router.use((req: Request, res: Response, next: express.NextFunction) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'POST, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

// 统一响应格式
interface ApiResponse {
  status: 'success' | 'error';
  message?: string;
  data?: any;
  errors?: any[];
}

// 用户注册
router.post(
  '/register',
  [
    body('userId').isString().isLength({ min: 1 }).withMessage('userId is required'),
    body('password').isString().isLength({ min: 1 }).withMessage('password is required')
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(400).json({
        status: 'error',
        errors: errors.array().map(err => ({ msg: err.msg }))
      } as ApiResponse);
      return;
    }

    const { userId, password } = req.body;
    try {
      await am.register(userId, password);
      res.json({
        status: 'success',
        message: 'User registered successfully',
        data: { success: true }
      } as ApiResponse);
    } catch (err: any) {
      if (err.message.includes('User already exists')) {
        res.status(409).json({
          status: 'error',
          message: 'User already exists'
        } as ApiResponse);
      } else {
        res.status(400).json({
          status: 'error',
          message: err.message
        } as ApiResponse);
      }
    }
  }
);

// 用户登录
router.post(
  '/login',
  [
    body('userId').isString().isLength({ min: 1 }).withMessage('userId is required'),
    body('password').isString().isLength({ min: 1 }).withMessage('password is required')
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(400).json({
        status: 'error',
        errors: errors.array().map(err => ({ msg: err.msg }))
      } as ApiResponse);
      return;
    }

    const { userId, password } = req.body;
    try {
      const authResult =  await am.login(userId, password);
      res.json({
        status: 'success',
        message: 'User logged in successfully',
        data: authResult
      } as ApiResponse);
    } catch (err: any) {
      res.status(401).json({
        status: 'error',
        message: 'Invalid userId or password'
      } as ApiResponse);
    }
  }
);

// 绑定第三方账号
router.post(
  '/code',
   authenticateJWT,
  [
    body('code').isString().isLength({ min: 1 }).withMessage('code is required'),
    //body('userId').isString().isLength({ min: 1 }).withMessage('userId is required'),
    body('brand').isIn(['xiaomi', 'midea']).withMessage('Invalid brand')
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(400).json({
        status: 'error',
        errors: errors.array().map(err => ({ msg: err.msg }))
      } as ApiResponse);
      return;
    }

    //const { code, userId, brand } = req.body;
    const { code, brand } = req.body;
    const userId = (req as any).user.userId; // 从 JWT 中提取

    try {
      const result = await am.exchangeCode(code, userId, brand);
      res.json({
        status: 'success',
        message: 'Code exchanged successfully',
        data: result
      } as ApiResponse);
    } catch (err: any) {
      res.status(500).json({
        status: 'error',
        message: err.message
      } as ApiResponse);
    }
  }
);

// 解绑第三方账号
router.post(
  '/unbind',
  authenticateJWT,
  [
    // body('userId').isString().isLength({ min: 1 }).withMessage('userId is required'),
    body('brand').isIn(['xiaomi', 'midea']).withMessage('Invalid brand')
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(400).json({
        status: 'error',
        errors: errors.array().map(err => ({ msg: err.msg }))
      } as ApiResponse);
      return;
    }

    // const { userId, brand } = req.body;
    const { brand } = req.body;
    const userId = (req as any).user.userId;
    try {
      await am.unbind(userId, brand);
      res.json({
        status: 'success',
        message: 'Account unbound successfully',
        data: { success: true }
      } as ApiResponse);
    } catch (err: any) {
      res.status(400).json({
        status: 'error',
        message: err.message
      } as ApiResponse);
    }
  }
);

// 获取授权码
router.post('/getAuthorizationCode', async (req, res) => {
  const { userId } = req.body;
  try {
    const authorizationCode = await auth.getAuthorizationCode(userId);
    if (authorizationCode) {
      res.json({ authorizationCode });
    } else {
      res.status(404).json({ error: 'User not found' });
    }
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});



// 刷新系统 accessToken（需要传入 refreshToken）
router.post(
    '/refresh-jwt',
    async (req, res):Promise<void> => {
  const { refreshToken } = req.body;

  if (!refreshToken || typeof refreshToken !== 'string') {
    res.status(400).json({
      status: 'error',
      message: 'refreshToken is required'
    } as ApiResponse);
    return;
  }

  try {
    const payload = verifyToken(refreshToken); // 验证 refreshToken（签名+过期）
    const newAccessToken = generateAccessToken({ userId: payload.userId });

    res.json({
      status: 'success',
      message: 'Token refreshed successfully',
      data: { token: newAccessToken }
    } as ApiResponse);
  } catch (err: any) {
    res.status(401).json({
      status: 'error',
      message: 'Invalid or expired refreshToken'
    } as ApiResponse);
  }
});


// 绑定状态查询
router.get('/bindings', authenticateJWT, async (req: Request, res: Response) => {
  const userId = (req as any).user.userId;

  try {
    const bindings = await am.getBindingStatus(userId);
    res.json({
      status: 'success',
      message: 'Fetched binding status',
      data: bindings
    });
  } catch (err: any) {
    res.status(500).json({
      status: 'error',
      message: err.message
    });
  }
});

// 授权页面路由
router.get('/auth-page/', (req: Request, res: Response) => {
  // 获取 HTML 文件的绝对路径
  const filePath = path.join(__dirname, '../../public/auth-page.html');

  // 发送 HTML 文件
  res.sendFile(filePath, (err) => {
    if (err) {
      console.error('Error sending auth-page.html:', err);
      res.status(500).send('Internal Server Error');
    }
  });
});




export default router;


